import _ from 'lodash';
import { reloadAuthorized } from './Authorized';
import { notification } from 'antd';
import { getPageQuery } from './utils';
import { message } from 'antd';
import { history } from 'umi';

export function getAuthority() {
  const authorityString = localStorage.getItem('ROUTE_AUTHORITY');
  let authority;

  try {
    if (authorityString) {
      authority = JSON.parse(authorityString);
    }
  } catch (e) {
    authority = authorityString;
  }

  if (typeof authority === 'string') {
    return [authority];
  } // preview.pro.ant.design only do not use in your production.
  // preview.pro.ant.design 专用环境变量，请不要在你的项目中使用它。

  if (!authority && ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION === 'site') {
    return ['admin'];
  }

  return authority;
}

export function getActionAuthority() {
  const actionAuthorityString = localStorage.getItem('ACTION_AUTHORITY');
  return JSON.parse(actionAuthorityString);
}

/*
    操作权限控制
    @param {string} key
    @param {boolean} hideMsg
    @return {boolean}
*/
export const widgetsControl = (key, hideMsg) => {
  const widgets = getActionAuthority();
  const hasPass = _.findLastIndex(widgets, item => {
    return item === key
  }) !== -1;
  if (!hasPass && !hideMsg) {
    notification.warning({
      message: '抱歉，您没有此操作权限',
      description: '如有需要，请联系管理员赋予权限',
      duration: 3
    });
  }
  return hasPass;
}

export function setAuthority(auths) {
  const routeAuthority = [];
  const actionAuthority = [];
  _.map(auths, (item) => {
    switch(Number(item.type)) {
      case 0:
      case 1:
      case 2:
        routeAuthority.push(item.action_key);
        break;
      case 3:
        actionAuthority.push(item.action_key);
        break;
    }
  });
  localStorage.setItem('ROUTE_AUTHORITY', JSON.stringify(routeAuthority));
  localStorage.setItem('ACTION_AUTHORITY', JSON.stringify(actionAuthority));

  reloadAuthorized();
}

export function redirectRoute(auths) {
  // 跳转处理
  const urlParams = new URL(window.location.href);
  const params = getPageQuery();
  message.success('登录成功！');
  let { redirect } = params;

  if (redirect) {
    const redirectUrlParams = new URL(redirect);

    if (redirectUrlParams.origin === urlParams.origin) {
      redirect = redirect.substr(urlParams.origin.length);
      if (window.routerBase !== '/') {
        redirect = redirect.replace(window.routerBase, '/');
      }
      if (redirect.match(/^\/.*#/)) {
        redirect = redirect.substr(redirect.indexOf('#') + 1);
      }
    } else {
      window.location.href = '/admin';
      return;
    }
  }

  history.replace(redirect || '/admin');
}
